package com.rankeiot.platform.service;

import com.rankeiot.core.data.response.Resp;
import com.rankeiot.core.util.SqlScriptRunner;
import com.rankeiot.platform.controller.InstallController;
import lombok.Data;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;

@Component
public class PlatformInstallListener {

    @EventListener
    public void onEvent(PlatformInstallEvent e) throws Throwable {
        //初始化平台数据库
        e.installSql("/META-INF/platform_mysql.sql");
    }

    @Data
    public static class PlatformInstallEvent {
        private InstallController.InstallConfig config;
        private Connection connection;

        public void installSql(String path) {
            SqlScriptRunner sr = new SqlScriptRunner(connection);
            URL url = PlatformInstallListener.class.getResource(path);//Utils.getResource(path);
            if(url!=null){
                try (InputStream in = url.openStream()) {
                    sr.runScript(new InputStreamReader(in));
                }catch (SQLException se){
                    se.printStackTrace();
                    Resp.fail(se.getMessage());
                }
                catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
